package db

import (
	"errors"
	"gorm.io/gorm"
	"hr/api/dto"
)

type BannerMenage struct {
	AppModel
	Title    string `gorm:"size:255" json:"title"`
	File     string `gorm:"size:255" json:"file"`
	Link     string `gorm:"size:255" json:"link"`
	CreateBy string `gorm:"size:128" json:"createBy"` // 创建人
	UpdateBy string `gorm:"size:128" json:"updateBy"` // 更新人
	Remark   string `gorm:"size:255" json:"remark"`   //备注
	Status   string `gorm:"size:64;" json:"status"`
}

func (m *BannerMenage) TableName() string {
	return "banner"
}

type BannerPageModel struct {
	Total    int64               `json:"total"`
	Result   []BannerMenage `json:"result"`
	PageNo   int                 `json:"pageNo"`
	PageSize int                 `json:"pageSize"`
}

func GetBannerPaging(pagination dto.Pagination, name string) (BannerPageModel, error) {
	result := BannerPageModel{
		Total:    0,
		Result:   make([]BannerMenage, 0),
		PageNo:   pagination.PageNo,
		PageSize: pagination.PageSize,
	}
	offset := (pagination.PageNo - 1) * pagination.PageSize
	dbs := GetInstance().Model(&BannerMenage{})
	if name != "" {
		dbs = dbs.Where("name LIKE ?", "%"+name+"%")
	}

	dbs = dbs.Order("created_at desc")

	if err := dbs.Offset(offset).Limit(pagination.PageSize).Find(&result.Result).Error; err != nil {
		return result, err
	}
	if err := dbs.Offset(-1).Limit(-1).Count(&result.Total).Error; err != nil {
		return result, err
	}
	return result, nil
}

// GetBanner 根据条件查找
func GetBanner(p map[string]interface{}) (BannerMenage, error, string) {
	f := BannerMenage{}
	err := GetInstance().Where(p).First(&f).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return f, errors.New("查无记录"), "0"
		}
		return f, errors.New(err.Error()), "1"
	}
	return f, nil, "2"
}

func CreateBanner(p dto.AdRequest, user string) (BannerMenage, error) {
	d := BannerMenage{
		Title:    p.Title,
		File:     p.File,
		Link:     p.Link,
		CreateBy: user,
		Remark:   p.Remark,
		Status:   p.Status,
	}
	if err := GetInstance().Create(&d).Error; err != nil {
		return d, err
	}
	return d, nil
}

func UpdateBanner(id uint, p dto.AdRequest, userId string) (BannerMenage, error) {
	f := BannerMenage{
		AppModel: AppModel{
			ID: id,
		},
	}
	err := GetInstance().Model(&f).Updates(BannerMenage{
		Title:    p.Title,
		File:     p.File,
		Link:     p.Link,
		UpdateBy: userId,
		Remark:   p.Remark,
		Status:   p.Status,
	}).Updates(map[string]interface{}{
		"id": id,
	}).Scan(&f).Error
	if err != nil {
		return f, err
	}
	return f, nil
}

func DeleteBanner(id uint) (BannerMenage, error) {
	f := BannerMenage{}
	err := GetInstance().Unscoped().Where("id = ?", id).Delete(&f).Error
	if err != nil {
		return f, err
	}
	return f, nil
}
